package cn.xfdzx.android.apps.shop.activity;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.luck.picture.lib.tools.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.adapter.AfterServiceGoodsListAdapter;
import cn.xfdzx.android.apps.shop.adapter.AfterServiceMarketGoodsRequestAdapter;
import cn.xfdzx.android.apps.shop.adapter.FullyGridLayoutManager;
import cn.xfdzx.android.apps.shop.adapter.GridImageSelAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.AfterMarketInfoBean;
import cn.xfdzx.android.apps.shop.bean.AfterMarketSelGoodsBean;
import cn.xfdzx.android.apps.shop.bean.AfterSalesListRetailBean;
import cn.xfdzx.android.apps.shop.bean.AfterServiceGoodsListBeen;
import cn.xfdzx.android.apps.shop.bean.AfterServiceUpLoadMoreImgBean;
import cn.xfdzx.android.apps.shop.bean.AfterServiceUpLoadSingImgBean;
import cn.xfdzx.android.apps.shop.bean.OrderDetailInfoBeen;
import cn.xfdzx.android.apps.shop.bean.OrderListBeen;
import cn.xfdzx.android.apps.shop.bean.OrderProcessBeen;
import cn.xfdzx.android.apps.shop.bean.ReturnReasonBean;
import cn.xfdzx.android.apps.shop.contract.AfterServiceContract;
import cn.xfdzx.android.apps.shop.presenter.AfterServicePresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.FileUtils;
import cn.xfdzx.android.apps.shop.util.GlideEngine;
import cn.xfdzx.android.apps.shop.util.KeybordUtil;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.SoftKeyBoardListener;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.widget.AfterServiceSelReasonWindow;
import cn.xfdzx.android.apps.shop.widget.WheelPicker;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/*批发申请退款商品-申请售后页面*/
public class AfterServiceMaraketGoods_RequestActivity extends BaseMvpActivity<AfterServicePresenter> implements AfterServiceContract.View {

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.recycle_goods)
    RecyclerView recycle_goods;
    @BindView(R.id.tv_submit)
    TextView tv_submit;//
    @BindView(R.id.rl_top)
    RelativeLayout rl_top;   //商品列表外部布局，用于监听软键盘设置焦点问题
    private TextView tv_selreason;//选择原因
    private TextView tv_returnmoney;//退款金额
    private TextView tv_yunfei;//运费
    private EditText ed_des;
    private double totalPrice;
    //private AfterServiceMarketGoodsAdapter goodsAdapter;
    private AfterServiceMarketGoodsRequestAdapter goodsAdapter;
    private List<AfterSalesListRetailBean.DataBean.ApplyBean> applyBeanList = new ArrayList<>();//商品列表
    private AfterServiceSelReasonWindow popupWindow;
    private WheelPicker wheelPicker;
    private List<String> reasonDate;
    private String selReason;
    private String type ="1";//区分0零售还是1批发
    private List<AfterMarketSelGoodsBean> selGoodsBeans = new ArrayList<>();
    private RecyclerView recycler_imgs;//列表图片
    private GridImageSelAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();//图片选择结果列表
    private boolean mode = true;//默认相册选择
    private List<MultipartBody.Part> upfiles = new ArrayList<>();//多图上传文件
    private String imgPathJson;//上传完成的图片路径json
    private String selGoodsListJson;//选择的商品json
    private List<AfterMarketSelGoodsBean> upGoodsList = new ArrayList<>();
    private String orderId;
    private OrderListBeen.DataBean dataBean;//订单原数据用于详情页面重新提交
    @Override
    public int getLayoutId() {
        return R.layout.activity_aftermarketlist_request;
    }

    @Override
    public void initView() {
        mPresenter = new AfterServicePresenter();
        mPresenter.attachView(this);
        dataBean = (OrderListBeen.DataBean) getIntent().getSerializableExtra("data");
        selGoodsBeans = (List<AfterMarketSelGoodsBean>) getIntent().getSerializableExtra("seldate");
        orderId = getIntent().getStringExtra("orderId");
        recycle_goods.setLayoutManager(new LinearLayoutManager(this));
        //cartInfo = dataBean.getCartInfo();
        goodsAdapter = new AfterServiceMarketGoodsRequestAdapter(selGoodsBeans);
        recycle_goods.setAdapter(goodsAdapter);
        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    PictureFileUtils.deleteCacheDirFile(AfterServiceMaraketGoods_RequestActivity.this, PictureConfig.TYPE_IMAGE);
                } else {
                    Toast.makeText(AfterServiceMaraketGoods_RequestActivity.this,
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
            }
        });
        View footView  = LayoutInflater.from(this).inflate(R.layout.activity_aftermarketlist_requestfootview, recycle_goods, false);
        tv_selreason = footView.findViewById(R.id.tv_selreason);
        recycler_imgs = footView.findViewById(R.id.recycler_img);
        tv_returnmoney = footView.findViewById(R.id.tv_returnmoney);
        ed_des = footView.findViewById(R.id.ed_des);
        goodsAdapter.addFooterView(footView);

        initListener();
        mPresenter.getReturnReason();
        initPopupWindow();
        setSoftKeyBoardListener();
    }

    private void initListener() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recycler_imgs.setLayoutManager(manager);
        adapter = new GridImageSelAdapter(this,onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(5);
        recycler_imgs.setAdapter(adapter);

        for (int i = 0; i < selGoodsBeans.size(); i++) {
            Log.e("totalPrice==",Double.parseDouble(selGoodsBeans.get(i).getGoodsPrice())*selGoodsBeans.get(i).getNum()+"==");
            totalPrice = Utils.addDouble(totalPrice,Double.parseDouble(selGoodsBeans.get(i).getGoodsPrice())*1);
            // totalPrice +=(double) selGoodsList.get(i).getPrice()*selGoodsList.get(i).getNumber();
        }
        tv_returnmoney.setText("¥"+ totalPrice);


        /**
         * 加减数量回调
         * */
        goodsAdapter.setItemAddMoveListener(new AfterServiceMarketGoodsRequestAdapter.OnItemOnClickListener() {
            @Override
            public void onItemAddMoveClick(int position, List<AfterMarketSelGoodsBean> selGoodsBeans) {
                totalPrice = 0.0;
                if (selGoodsBeans.size()>0){

                    //selGoodsList.get(position).setPrice(Double.parseDouble(date.getProductInfo().getPrice()));

                    for (int i = 0; i < selGoodsBeans.size(); i++) {
                        Log.e("totalPrice==",Double.parseDouble(selGoodsBeans.get(i).getGoodsPrice())*selGoodsBeans.get(i).getNum()+"==");
                        totalPrice = Utils.addDouble(totalPrice,Double.parseDouble(selGoodsBeans.get(i).getGoodsPrice())*selGoodsBeans.get(i).getNum());
                        // totalPrice +=(double) selGoodsList.get(i).getPrice()*selGoodsList.get(i).getNumber();
                    }
                    tv_returnmoney.setText("¥"+ totalPrice);
                }
            }
        });
    }

    private void initPopupWindow() {
        popupWindow = new AfterServiceSelReasonWindow(this, R.layout.pw_selreason,type);
        wheelPicker = popupWindow.getRootView().findViewById(R.id.up_unit);


        popupWindow.getRootView().findViewById(R.id.tv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.shareClose();
            }
        });

        ((TextView) popupWindow.getRootView().findViewById(R.id.tv_queren)).setTextColor(getResources().getColor(R.color.color_02C557));

        popupWindow.getRootView().findViewById(R.id.tv_queren).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selReason = reasonDate.get(wheelPicker.getCurrentPosition());
                tv_selreason.setText(selReason);
                popupWindow.shareClose();
            }
        });

        tv_selreason.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.showPopupWindow();
            }
        });

    }

    private GridImageSelAdapter.onAddPicClickListener onAddPicClickListener = new GridImageSelAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            showPublishDialog();
//            if (mode) {
//                // 进入相册 以下是例子：不需要的api可以不写
//                getBitmapFromGallery();
//            } else {
//                // 单独拍照
//                getBitmapFromCamera();
//            }
        }

    };

    public void showPublishDialog() {
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }

            String[] permissions2 = {Manifest.permission.INTERNET,Manifest.permission.ACCESS_NETWORK_STATE,Manifest.permission.ACCESS_WIFI_STATE};
            //验证是否许可权限
            for (String str : permissions2) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions2, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }
        getBitmapFromGallery();

    }
    @Override
    public void showLoading() {
        if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
            ProgressDialog.getInstance().show(this);
        }
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }

    @Override
    public void onError(Throwable throwable) {
        Log.e("异常", throwable.toString());
        Utils.toastMessage(this,"网络连接异常");
    }

    @Override
    public void onUploadMoreImgSuccess(AfterServiceUpLoadMoreImgBean bean) {
        hideLoading();
        if (bean.getErrno().equals("200")){
            requestAfterServiceMore(bean);
        }else {
            ToastUtils.s(this,bean.getMessage());
        }
    }

    @Override
    public void onUploadSingImgSuccess(AfterServiceUpLoadSingImgBean bean) {
        hideLoading();
        if (bean.getErrno().equals("200")){
            requestAfterServiceSing(bean);
        }else {
            ToastUtils.s(this,bean.getMessage());
        }
    }

    /**
     * 上传多图完成
     * */
    private void requestAfterServiceMore(AfterServiceUpLoadMoreImgBean bean) {
        imgPathJson = new Gson().toJson(bean.getData().getSrc());
        Log.e("selGoodsList",imgPathJson+"-imgPathJson-");

        for (int i = 0; i < selGoodsBeans.size(); i++) {
            upGoodsList.add(new AfterMarketSelGoodsBean(selGoodsBeans.get(i).getGoods_id(),selGoodsBeans.get(i).getNum()));
        }
        selGoodsListJson = new Gson().toJson(upGoodsList);

        Map<String,Object> map = new HashMap<>();
        map.put("orderId",orderId);
        map.put("reason",selReason);
        if (EmptyUtil.isNotEmpty(ed_des.getText().toString())){
            map.put("desc",ed_des.getText().toString().trim());
        }
        map.put("img",imgPathJson);
        map.put("goods",selGoodsListJson);
        mPresenter.getMarketAfterServiceRequest(map);
    }

    /**
     * 上传单图完成
     * */
    private void requestAfterServiceSing(AfterServiceUpLoadSingImgBean bean) {
        imgPathJson = "["+new Gson().toJson(bean.getData().getSrc())+"]";
        Log.e("selGoodsList",imgPathJson+"-imgPathJson-");
        for (int i = 0; i < selGoodsBeans.size(); i++) {
            upGoodsList.add(new AfterMarketSelGoodsBean(selGoodsBeans.get(i).getGoods_id(),selGoodsBeans.get(i).getNum()));
        }
        selGoodsListJson = new Gson().toJson(upGoodsList);

        Map<String,Object> map = new HashMap<>();
        map.put("orderId",orderId);
        map.put("reason",selReason);
        if (EmptyUtil.isNotEmpty(ed_des.getText().toString())){
            map.put("desc",ed_des.getText().toString().trim());
        }
        map.put("img",imgPathJson);
        map.put("goods",selGoodsListJson);
        mPresenter.getMarketAfterServiceRequest(map);
    }



    @Override
    public void getReturnReasonSuccess(ReturnReasonBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (EmptyUtil.isNotEmpty(bean.getData())){
                reasonDate = bean.getData();
                wheelPicker.setDataList(reasonDate);

            }

        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getAfterServiceRequestSuccess(OrderProcessBeen bean) {

    }

    @Override
    public void getAfterServiceCancleSuccess(ReturnReasonBean bean) {

    }

    @Override
    public void getAfterServiceProgressSuccess(OrderProcessBeen bean) {

    }

    @Override
    public void getOrderDetailSuccess(OrderDetailInfoBeen bean) {

    }

    @Override
    public void getMarketAfterServiceRequestSucces(OrderProcessBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            Intent intent = new Intent(this,AfterServiceInfoMarketActivity.class);
            intent.putExtra("applyId",bean.getData().getApply_id());
            intent.putExtra("data", dataBean);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

     @Override
    public void getMarketAfterServiceCancleSucces(ReturnReasonBean bean) {

    }

    @Override
    public void getMarketAfterServiceInfoSucces(AfterMarketInfoBean bean) {

    }

    @OnClick({R.id.iv_back,R.id.tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:    //返回按钮点击
                finish();
                break;
            case R.id.tv_submit:    //确定按钮点击
                if (EmptyUtil.isEmpty(selReason)){
                    ToastUtils.s(this,"请选择退款原因");
                    return;
                }
                if (EmptyUtil.isEmpty(selectList)){
                    ToastUtils.s(this,"请上传图片");
                    return;
                }
                upload();

//                for (int i = 0; i < cartInfo.size(); i++) {
//                    if (cartInfo.get(i).isAfterCheck()){
//                        selGoodsBeans.add(new AfterMarketSelGoodsBean(
//                                cartInfo.get(i).getProduct_id()+"",
//                                cartInfo.get(i).getProductInfo().getStore_name(),
//                                cartInfo.get(i).getProductInfo().getUnit_name(),
//                                cartInfo.get(i).getProductInfo().getImage(),
//                                cartInfo.get(i).getCart_num()));
//                    }
//                }
//
//                if (EmptyUtil.isEmpty(selGoodsBeans)){
//                    Utils.toastMessage(this,"请选择要售后的商品");
//                    return;
//                }
//
//                Intent intent = new Intent(this,AfterServiceInfoActivity.class);
//                intent.putExtra("date", (Serializable) selGoodsBeans);
//                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**相册**/
    private void getBitmapFromGallery() {
        // 相册
        PictureSelector.create(AfterServiceMaraketGoods_RequestActivity.this)
                .openGallery(PictureMimeType.ofImage())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
//                .theme(themeId)// 主题样式设置 具体参考 values/styles
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(5)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
//                .previewVideo(cb_preview_video.isChecked())// 是否可预览视频
//                .enablePreviewAudio(cb_preview_audio.isChecked()) // 是否可播放音频
                .isCamera(true)// 是否显示拍照按钮
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .compressQuality(90)
                .glideOverride(130, 130)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(3, 4)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                .hideBottomControls(cb_hide.isChecked() ? false : true)// 是否显示uCrop工具栏，默认不显示
//                .isGif(cb_isGif.isChecked())// 是否显示gif图片
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(false)// 是否圆形裁剪
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .openClickSound(false)// 是否开启点击声音
                .selectionMedia(selectList)// 是否传入已选图片
                .previewEggs(false)//预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                //.cropCompressQuality(90)// 裁剪压缩质量 默认为100
                .minimumCompressSize(100)// 小于1000kb的图片不压缩
                //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                //.rotateEnabled() // 裁剪是否可旋转图片
                //.scaleEnabled()// 裁剪是否可放大缩小图片
                //.videoQuality()// 视频录制质量 0 or 1
                //.videoSecond()////显示多少秒以内的视频or音频也可适用
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    upfiles.clear();
                    for (LocalMedia media : selectList) {
                        Log.i("图片-----》", media.getPath());
                    }
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();

                    //upload();
                    break;
            }
        }
    }

    /**上传多张图片*/
    private void uploadImg(File file, String fileName) {

        try{
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            builder.addFormDataPart("file[]", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file));
            MultipartBody.Part part = MultipartBody.Part.createFormData("file[]", fileName+".jpg", RequestBody.create(MediaType.parse("image/jpg"), file));
            upfiles.add(part);

        }catch (Exception e){
            ToastUtils.s(this,"当前网络状态不佳，上传失败，请稍后再试");
        }

    }

    /**上传图片之后申请售后*/
    private void upload() {
        upfiles.clear();
        for (LocalMedia media : selectList) {

            Log.i("图片-----》", media.getPath()+ "-----"+ media.position);

            if (EmptyUtil.isNotEmpty(media.getCompressPath())){
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(media.getCompressPath());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        Bitmap bitmap  = BitmapFactory.decodeStream(fis);
                        File file = FileUtils.getFile(bitmap,"afterserviceImg"+media.position);
                        Log.e("filelengh",media.position+"=="+file.length()+"图片大小");
                        uploadImg(file,"afterserviceImg"+ media.position);
                        if(null != fis){
                            fis.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

        }

        //Log.e("upfiles","upfiles上传图片"+upfiles.size());
        try{
            //服务器单张和多张返回类型不同，调用不同方法
            if (upfiles.size()>1){
                mPresenter.uploadMoreImg(upfiles);
            }else {
                mPresenter.uploadSingImg(upfiles);
            }
            showLoading();
        }catch (Exception e){
            Log.e("Exception",e.toString());
        }



    }

    /**
     * 添加软键盘监听
     */
    private void setSoftKeyBoardListener() {
        SoftKeyBoardListener softKeyBoardListener = new SoftKeyBoardListener(this);
        //软键盘状态监听
        softKeyBoardListener.setListener(new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                //软键盘已经显示，做逻辑

            }

            @Override
            public void keyBoardHide(int height) {
                //软键盘已经隐藏,做逻辑
                rl_top.requestFocus();
                rl_top.setFocusable(true);
                rl_top.setFocusableInTouchMode(true);
            }
        });
    }
}
